<?php

/**
 * ---------------------------------------------------------------------
 *
 * GLPI - Gestionnaire Libre de Parc Informatique
 *
 * http://glpi-project.org
 *
 * @copyright 2015-2025 Teclib' and contributors.
 * @copyright 2003-2014 by the INDEPNET Development Team.
 * @licence   https://www.gnu.org/licenses/gpl-3.0.html
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * ---------------------------------------------------------------------
 */

namespace Glpi\Form\Destination;

use Glpi\DBAL\JsonFieldInterface;
use Glpi\Form\AnswersSet;
use Glpi\Form\Export\Context\DatabaseMapper;
use Glpi\Form\Export\Serializer\DynamicExportDataField;
use Glpi\Form\Form;
use LogicException;
use Override;
use Toolbox;

abstract class AbstractConfigField implements DestinationFieldInterface
{
    #[Override]
    final public static function getKey(): string
    {
        return Toolbox::slugify(static::class);
    }

    #[Override]
    public function supportAutoConfiguration(): bool
    {
        return false;
    }

    #[Override]
    public function getAutoGeneratedConfig(Form $form): ?JsonFieldInterface
    {
        return null;
    }

    #[Override]
    public function applyConfiguratedValueToInputUsingAnswers(
        JsonFieldInterface $config,
        array $input,
        AnswersSet $answers_set
    ): array {
        // Nothing to do by default
        return $input;
    }

    #[Override]
    public function applyConfiguratedValueAfterDestinationCreation(
        FormDestination $destination,
        JsonFieldInterface $config,
        AnswersSet $answers_set,
        array $created_objects
    ): void {
        // Nothing to do by default
    }

    public function getConfig(Form $form, array $config): JsonFieldInterface
    {
        if ($this->supportAutoConfiguration() && $this->isAutoConfigurated($config)) {
            $config = $this->getAutoGeneratedConfig($form);
            if ($config === null) {
                throw new LogicException(
                    "getAutoGeneratedConfig can't return null if supportAutoConfiguration is true"
                );
            }

            return $config;
        }

        // Try to load config if defined
        $config = $config[static::getKey()] ?? null;
        if ($config === null) {
            return $this->getDefaultConfig($form);
        }

        $config_class = $this->getConfigClass();
        return $config_class::jsonDeserialize($config);
    }

    public function isAutoConfigurated(array $config): bool
    {
        return $config[static::getAutoConfigKey()] ?? true;
    }

    public static function getAutoConfigKey(): string
    {
        return static::getKey() . '_auto';
    }

    #[Override]
    public function prepareInput(array $input): array
    {
        $config_class = $this->getConfigClass();

        /**
         * All strategies are submitted as an array, even if the field can only have one strategy at a time.
         * The field should handle this and only use the first strategy if it can only have one.
         */
        if (is_subclass_of($config_class, ConfigFieldWithStrategiesInterface::class)) {
            /** @var class-string<ConfigFieldWithStrategiesInterface> $config_class */
            if (
                $this->canHaveMultipleStrategies() === false
                && is_array($input[static::getKey()][$config_class::getStrategiesInputName()] ?? null)
            ) {
                $input[static::getKey()][$config_class::getStrategiesInputName()] = $input[static::getKey()][$config_class::getStrategiesInputName()][0];
            }
        }

        return $input;
    }

    public function getStrategiesForDropdown(): array
    {
        return [];
    }

    public function canHaveMultipleStrategies(): bool
    {
        return false;
    }

    /**
     * Returns an array of reusable strategies that can be used multiple times in the same field configuration.
     * This is useful for fields that can have multiple instances of the same strategy.
     *
     * @return array<string> Strategie enum values that can be reused.
     */
    public function getReusableStrategies(): array
    {
        return [];
    }

    public function exportDynamicConfig(
        array $config,
        AbstractCommonITILFormDestination $destination,
    ): DynamicExportDataField {
        return new DynamicExportDataField($config, []);
    }

    public static function prepareDynamicConfigDataForImport(
        array $config,
        AbstractCommonITILFormDestination $destination,
        DatabaseMapper $mapper,
    ): array {
        return $config;
    }
}
